import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Input, Button, Table, message, Select, Checkbox, Space, DatePicker } from 'antd'
import { UpOutlined, DownOutlined } from '@ant-design/icons'
// import moment from 'moment'
import _ from 'loadsh'
import { addWindow } from '@redux/actions'
import style from '@pages/filingCaseManage/CaseManage.module.less'
import Dictionary from '@js/dictionary'
import { compressLicenseAndMobile, decomporessListLicenseAndMobileAndBank, strToNum } from '@src/assets/js/tool'
import EditModal from './components/EditModal'
import moment from 'moment'

const { Item } = Form
const { Option } = Select
const { RangePicker } = DatePicker
const layout = {
  labelCol: { flex: '120px' }
}

// 获取表格字段配置
function getColumns () {
  return [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      width: 80
    },
    {
      title: '专业',
      dataIndex: 'professional',
      key: 'professional',
      width: 200
    },
    {
      title: '学历',
      dataIndex: 'educational',
      key: 'educational',
      width: 100
    },
    {
      title: '擅长领域',
      dataIndex: 'special',
      key: 'special',
      width: 200
    },
    {
      title: '单位',
      dataIndex: 'structure',
      key: 'structure',
      width: 100
    },
    {
      title: '职业',
      dataIndex: 'occupation',
      key: 'occupation',
      width: 100
    },
    {
      title: '操作',
      dataIndex: 'index',
      key: 'operate',
      width: 60,
      render: (value, line) => {
        return <span className={style['link-btn']} onClick={() => this.modifyDetail(line)}>修改</span>
      }
    }
  ]
}

class ArbitratorList extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    },
    areaOptions: ['哈尔滨市', '齐齐哈尔市', '牡丹江市', '佳木斯市', '大庆市', '鸡西市', '双鸭山市', '鹤岗市', '七台河市', '伊春市', '黑河市', '绥化市', '大兴安岭地区', '外省', '外籍'],
    detailAreaOptions: [],
    areaMap: {},
    occupationMap: {},
    detailAreaVisible: false,
    areaIndeterminate: false,
    areaCheckAll: true,
    areaCheckedList: [],
    typeOptions: [],
    typeIndeterminate: false,
    typeCheckAll: true,
    typeCheckedList: [],
    majors: [],
    detailData: null,
    detailVisible: false,
    causeactionClassList: [],
    caseTypeOptions: [],
    treeData: []
  }

  formRef = React.createRef()

  detailFormRef = React.createRef()

  // 改变案件状态
  changeStatus (status) {
    this.setState({
      status,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  searchHandle (d) {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData(d)
    })
  }

  // 获取查询参数
  getParams (form) {
    const { pagination, status, typeCheckedList, areaMap } = this.state
    let areaCheckedList = this.state.areaCheckedList.slice()
    const { current, pageSize } = pagination
    form = form || this.formRef.current.getFieldsValue()
    const condition = []
    if (areaCheckedList.length) {
      const otherIndex = areaCheckedList.indexOf('外省')
      if (otherIndex !== -1) {
        areaCheckedList.splice(otherIndex, 1)
        areaCheckedList = [...areaCheckedList, ...(areaMap['外省'] || [])]
      }
      const foreignIndex = areaCheckedList.indexOf('外籍')
      if (foreignIndex !== -1) {
        areaCheckedList.splice(foreignIndex, 1)
        areaCheckedList = [...areaCheckedList, ...(areaMap['外籍'] || [])]
      }
      condition.push({ k: 'area', o: 'in', v: areaCheckedList.join(',') })
    }
    if (typeCheckedList.length) {
      condition.push({ k: 'occupation', o: 'in', v: typeCheckedList.join(',') })
    }
    if (form.name !== undefined && form.name !== '') {
      condition.push({ k: 'name', o: 'like', v: `%${form.name}%` })
    }
    if (form.retire !== undefined && form.retire !== '') {
      condition.push({ k: 'retire', o: '=', v: form.retire })
    }
    if (form.foreign_case_in !== undefined && form.foreign_case_in !== '') {
      condition.push({ k: 'foreign_case_in', o: '=', v: form.foreign_case_in })
    }
    if (form.gender !== undefined && form.gender !== '') {
      condition.push({ k: 'gender', o: '=', v: form.gender })
    }
    if (form.special !== undefined && form.special !== '') {
      condition.push({ k: 'special', o: 'like', v: `%${form.special}%` })
    }
    if (form.professional !== undefined && form.professional !== '') {
      condition.push({ k: 'professional', o: 'like', v: `%${form.professional}%` })
    }
    if (form.first_appoint_datetime && form.first_appoint_datetime.length > 0) {
      const b = form.first_appoint_datetime[0]
      const e = form.first_appoint_datetime[1]
      condition.push({ k: 'first_appoint_datetime', o: '>=', v: Math.floor(moment(`${b.format('YYYY-MM-DD')} 00:00:00`) / 1000) })
      condition.push({ k: 'first_appoint_datetime', o: '<=', v: Math.floor(moment(`${e.format('YYYY-MM-DD')} 23:59:59`) / 1000) })
    }
    if (form.causeaction_class) {
      condition.push({ k: 'causeaction_class', o: 'like', v: `%${form.causeaction_class}%` })
    }
    if (form.professional_class === '金融') {
      condition.push({ k: 'professional_class', o: '=', v: '金融' })
    } else if (form.professional_class === '非金融') {
      condition.push({ k: 'professional_class ', o: 'null' })
    }
    if (form.structure) {
      condition.push({ k: 'structure', o: 'like', v: `%${form.structure}%` })
    }
    if (form.residence_address) {
      condition.push({ k: 'residence_address', o: 'like', v: `%${form.residence_address}%` })
    }
    if (form.educational && form.educational !== '全部') {
      condition.push({ k: 'educational', o: '=', v: form.educational })
    }
    const data = {
      current,
      page_size: pageSize,
      status,
      condition: JSON.stringify(condition)
    }
    return data
  }

  // 获取案由
  getTreeData () {
    this.$get('/api/common/cause_action')
      .then(res => {
        if (res.status === 1 && res.data instanceof Array) {
          this.setState({ treeData: res.data })
        }
      })
  }

  // 获取仲裁员数据
  getTableData (form) {
    form = form || this.formRef.current.getFieldsValue()
    const { pagination } = this.state
    const { current, pageSize } = pagination
    this.setState({ loading: true })
    this.$get('/api/xapc/arbitrator', this.getParams(form)).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        decomporessListLicenseAndMobileAndBank(res.data.list)
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          }
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange ({ current, pageSize }) {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 重置表格
  resetHandle (callback = () => {}) {
    this.formRef.current.resetFields()
    this.setState({
      areaCheckAll: true,
      areaIndeterminate: false,
      typeCheckAll: true,
      detailAreaVisible: false,
      areaCheckedList: this.state.areaOptions.slice(),
      typeCheckedList: this.state.typeOptions.slice(),
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  // 格式化所在区域
  formatArea (data) {
    const keys = Object.keys(data)
    let result = []
    keys.forEach(key => {
      result = [...result, ...data[key]]
    })
    this.setState({
      detailAreaOptions: result,
      areaCheckedList: this.state.areaOptions.slice(),
      areaMap: data
    })
  }

  // 从字典中获取仲裁员类型
  getTypeFromDictionary () {
    const d = new Dictionary()
    d.init('仲裁员职业分类,仲裁员办案情况')
      .then(() => {
        const ocTypes = d.getList('仲裁员职业分类')
        const typeOptions = (ocTypes).map(li => li.title)
        this.setState({
          occupationMap: ocTypes,
          typeOptions,
          typeCheckedList: typeOptions.slice(),
          caseTypeOptions: d.getList('仲裁员办案情况')
        })
      })
  }

  // 获取所在区域
  getAreaMap () {
    return this.$get('/api/xapc/arbitrator/area')
      .then(res => {
        if (res.status === 1) {
          this.formatArea(res.data)
        } else {
          message.warning(res.message)
        }
      })
  }

  // 获取专业
  getDictionary () {
    return this.$get('/api/xapc/dictionary', {
      types: '专业'
    }).then(res => {
      if (res.status === 1) {
        this.setState({
          majors: res.data[0].list.map(li => li.value)
        })
      } else {
        message.error(res.message)
      }
    })
  }

  // 改变多选项
  changeCheckbox (type, list) {
    const options = this.state[type + 'Options']
    this.setState({
      [type + 'CheckedList']: list,
      [type + 'Indeterminate']: !!list.length && list.length < options.length,
      [type + 'CheckAll']: list.length === options.length
    })
  }

  // 点击全选按钮
  changeAll (type, e) {
    this.setState({
      [type + 'CheckedList']: e.target.checked ? this.state[type + 'Options'] : [],
      [type + 'Indeterminate']: false,
      [type + 'CheckAll']: e.target.checked
    })
  }

  // 改变选中项
  onSelectChange = selectedRowKeys => {
    const { current, pageSize } = this.state.pagination
    const i = selectedRowKeys[0] - (current - 1) * pageSize
    const o = this.state.list[i]
    if (this.props.disabledIdList.indexOf(o.id) !== -1) {
      return false
    }
    this.setState({ selectedRowKeys }, () => {
      this.props.onChange({ arbitrator: o.name, arbitratorid: o.id })
    })
  }

  // 全选区域
  changeAllArea (e) {
    const options = this.state.detailAreaVisible ? this.state.detailAreaOptions : this.state.areaOptions
    this.setState({
      areaCheckedList: e.target.checked ? options : [],
      areaIndeterminate: false,
      areaCheckAll: e.target.checked
    })
  }

  // 改变区域多选项
  changeAreaCheckbox (list, callback = () => {}) {
    const options = this.state.detailAreaVisible ? this.state.detailAreaOptions : this.state.areaOptions
    this.setState({
      areaCheckedList: list,
      areaIndeterminate: !!list.length && list.length < options.length,
      areaCheckAll: list.length === options.length
    }, callback)
  }

  // 展开详细区域
  showDetailArea () {
    this.setState({
      detailAreaVisible: true
    }, () => {
      if (this.state.areaCheckAll) {
        this.changeAreaCheckbox(this.state.detailAreaOptions)
      } else {
        let list = []
        const checkedList = this.state.areaCheckedList
        const areaMap = this.state.areaMap
        const areaList = ['哈尔滨市', '齐齐哈尔市', '牡丹江市', '佳木斯市', '大庆市', '鸡西市', '双鸭山市', '鹤岗市', '七台河市', '伊春市', '黑河市', '绥化市', '大兴安岭地区']
        areaList.forEach(li => {
          if (checkedList.indexOf(li) !== -1) {
            list.push(li)
          }
        })
        if (checkedList.indexOf('外省') !== -1) {
          list = [...list, ...(areaMap['外省'] || [])]
        }
        if (checkedList.indexOf('外籍') !== -1) {
          list = [...list, ...(areaMap['外籍'] || [])]
        }
        this.changeAreaCheckbox(list)
      }
    })
  }

  // 隐藏详细区域
  hideDetailArea () {
    this.setState({
      detailAreaVisible: false
    }, () => {
      if (this.state.areaCheckAll) {
        this.changeAreaCheckbox(this.state.areaOptions)
      } else {
        const list = []
        const checkedList = this.state.areaCheckedList
        const areaMap = this.state.areaMap
        const hasOther = (areaMap['外省'] || []).every(a => checkedList.indexOf(a) !== -1)
        const hasForeign = (areaMap['外籍' || []]).every(a => checkedList.indexOf(a) !== -1)
        const areaList = ['哈尔滨市', '齐齐哈尔市', '牡丹江市', '佳木斯市', '大庆市', '鸡西市', '双鸭山市', '鹤岗市', '七台河市', '伊春市', '黑河市', '绥化市', '大兴安岭地区']
        areaList.forEach(li => {
          if (checkedList.indexOf(li) !== -1) {
            list.push(li)
          }
        })
        if (hasOther) {
          list.push('外省')
        }
        if (hasForeign) {
          list.push('外籍')
        }
        this.changeAreaCheckbox(list)
      }
    })
  }

  // 获取基础数据
  getBaseData () {
    Promise.all([this.getAreaMap(), this.getTypeFromDictionary(), this.getDictionary(), this.getCauseactionClassList()])
      .then(() => {
        this.initForm()
      })
  }

  // 设置要修改的仲裁员详情
  modifyDetail (l) {
    l = _.cloneDeep(l)
    l.professional = typeof l.professional === 'string' ? l.professional.split(',') : []
    l.cause_action = typeof l.cause_action === 'string' ? l.cause_action.split(',') : []
    l.special = typeof l.special === 'string' ? l.special.split(',') : []
    l.caseon_info = typeof l.caseon_info === 'string' ? l.caseon_info.split(',') : []
    l.first_appoint_datetime = strToNum(l.first_appoint_datetime)
    l.birthday = strToNum(l.birthday)
    if (l.first_appoint_datetime) {
      l.first_appoint_datetime = moment(l.first_appoint_datetime * 1000)
    }
    if (l.birthday) {
      l.birthday = moment(l.birthday * 1000)
    }
    const keys = Object.keys(l)
    keys.forEach(key => {
      if (l[key] === null) {
        l[key] = undefined
      }
    })
    if (!(l.special instanceof Array)) {
      l.special = []
    }
    this.setState({
      detailData: l,
      detailVisible: true
    })
  }

  // 更新仲裁员详情
  updateDetail (d) {
    const hide = message.loading('更新中', 120)
    d.professional = (d.professional || []).join()
    d.cause_action = (d.cause_action || []).join()
    d.caseon_info = (d.caseon_info || []).join()
    d.special = (d.special || []).join()
    if (d.birthday) {
      d.birthday = Math.floor(moment(`${d.birthday.format('YYYY-MM')}-01 00:00:00`).valueOf() / 1000)
    }
    if (d.first_appoint_datetime) {
      d.first_appoint_datetime = Math.floor(moment(`${d.first_appoint_datetime.format('YYYY-MM-DD')} 00:00:00`).valueOf() / 1000)
    }
    compressLicenseAndMobile(d)
    this.$put(`/api/xapc/arbitrator/${d.id}`, d)
      .then(res => {
        hide()
        if (res.status === 1) {
          this.setState({
            detailData: null,
            detailVisible: false
          }, () => {
            this.getTableData()
          })
        } else {
          message.warning(res.message)
        }
      })
      .catch(() => hide())
  }

  // 初始化表格
  initForm () {
    const formData = this.props.meta.formData || {}
    const c = this.formRef.current
    this.resetHandle(() => {
      if (formData.gender !== undefined || formData.retire !== undefined) {
        c.setFieldsValue(formData)
        this.getTableData()
      } else if (formData.areatype) {
        this.hideDetailArea()
        this.changeAreaCheckbox(formData.areatype, () => {
          this.setState({
            areaCheckedList: formData.areatype,
            areaCheckAll: false,
            areaIndeterminate: true
          }, () => {
            this.getTableData()
          })
        })
      } else if (formData.occupation !== undefined) {
        this.setState({
          typeCheckedList: [formData.occupation],
          typeCheckAll: false
        }, () => {
          this.getTableData()
        })
      } else {
        this.getTableData()
      }
    })
  }

  // 获取专业小项
  getCauseactionClassList () {
    return this.$get('/api/xapc/dictionary/getTreeByType', {
      type: '案件分类'
    }).then(res => {
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      const arr = res.data.filter(li => li.value === '金融案件')
      const l = arr[0].children.map(li => li.value)
      this.setState({
        causeactionClassList: l
      })
    })
  }

  componentDidUpdate (prev) {
    if (prev.meta !== this.props.meta) {
      this.initForm()
    }
  }

  componentDidMount () {
    this.getTreeData()
    this.getBaseData()
  }

  // 渲染搜索表单的展开和收起
  renderToggleBtns () {
    if (this.state.searchToggleBtn) {
      return (
        <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
          <span>展开</span>
          <UpOutlined />
        </Button>
      )
    }
    return (
      <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
        <span>收起</span>
        <DownOutlined />
      </Button>
    )
  }

  render () {
    const columns = getColumns.call(this)
    const initialValues = {
      retire: '',
      foreign_case_in: '',
      gender: '',
      employmentTime: '全部',
      professional_class: '全部',
      educational: '全部'
    }
    return (
      <div className={style.container}>
        <EditModal visible={this.state.detailVisible} hide={() => { this.setState({ detailVisible: false, detailData: null }) }} data={this.state.detailData} majors={this.state.majors} treeData={this.state.treeData} typeOptions={this.state.typeOptions} caseTypeOptions={this.state.caseTypeOptions} callback={d => this.updateDetail(d)} />
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form name='my_case_manage' {...layout} initialValues={initialValues} ref={this.formRef} onFinish={v => this.searchHandle(v)}>
              <Row>
                <Col span={8}>
                  <Item label='名称' name='name'>
                    <Input placeholder='请输入' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='工作状况' name='retire'>
                    <Select placeholder='请选择'>
                      <Option value=''>全部</Option>
                      <Option value={0}>在职</Option>
                      <Option value={1}>非在职</Option>
                    </Select>
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='擅长涉外' name='foreign_case_in'>
                    <Select placeholder='请选择'>
                      <Option value=''>全部</Option>
                      <Option value={1}>是</Option>
                      <Option value={0}>不是</Option>
                    </Select>
                  </Item>
                </Col>
              </Row>
              <Row>
                <Col span={8}>
                  <Item label='擅长领域' name='special'>
                    <Input placeholder='请输入' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='专业' name='special'>
                    <Select className={style.full} placeholder='请选择' showSearch allowClear>
                      {
                        this.state.majors.map(li => <Option key={li} value={li}>{li}</Option>)
                      }
                    </Select>
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='性别' name='gender'>
                    <Select className={style.full} placeholder='请选择' allowClear>
                      <Option value=''>全部</Option>
                      <Option value='男'>男</Option>
                      <Option value='女'>女</Option>
                    </Select>
                  </Item>
                </Col>
              </Row>
              <Row>
                <Col span={8}>
                  <Item label='初任仲裁员时间' name='first_appoint_datetime'>
                    <RangePicker className={style.full} />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='所在单位' name='structure'>
                    <Input placeholder='请输入' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='居住地' name='residence_address'>
                    <Input placeholder='请输入' />
                  </Item>
                </Col>
              </Row>
              <Row>
                <Col span={8}>
                  <Item label='学历' name='educational'>
                    <Select className={style.full} placeholder='请选择' allowClear>
                      <Option value=''>全部</Option>
                      <Option value='专科'>专科</Option>
                      <Option value='本科'>本科</Option>
                      <Option value='硕士研究生'>硕士研究生</Option>
                      <Option value='博士研究生'>博士研究生</Option>
                    </Select>
                  </Item>
                </Col>
              </Row>
              <Item label='所在区域'>
                <div>
                  <Checkbox
                    indeterminate={this.state.areaIndeterminate}
                    onChange={e => this.changeAllArea(e)}
                    checked={this.state.areaCheckAll}
                    style={{ marginTop: '5px' }}
                  >全选
                  </Checkbox>
                  {this.state.detailAreaVisible ? (
                    <>
                      <div className={style['detail-area']}>
                        <Checkbox.Group
                          options={this.state.detailAreaOptions}
                          value={this.state.areaCheckedList}
                          onChange={v => this.changeAreaCheckbox(v)}
                        />
                        <Button type='link' onClick={() => this.hideDetailArea()}>收起</Button>
                      </div>
                    </>
                  ) : (
                    <>
                      <Checkbox.Group
                        options={this.state.areaOptions}
                        value={this.state.areaCheckedList}
                        onChange={v => this.changeAreaCheckbox(v)}
                      />
                      <Button type='link' onClick={() => this.showDetailArea()}>更多</Button>
                    </>
                  )}
                </div>
              </Item>
              <Item label='职业分类'>
                <div>
                  <Checkbox
                    indeterminate={this.state.typeIndeterminate}
                    onChange={e => this.changeAll('type', e)}
                    checked={this.state.typeCheckAll}
                  >全选
                  </Checkbox>
                  <Checkbox.Group
                    options={this.state.typeOptions}
                    value={this.state.typeCheckedList}
                    onChange={v => this.changeCheckbox('type', v)}
                  />
                </div>
              </Item>
              <Row gutter={24}>
                <Item className={style['right-line']}>
                  <Space size='middle'>
                    <Button type='primary' ghost htmlType='submit'>搜索</Button>
                    <Button htmlType='reset' onClick={() => this.resetHandle()}>重置</Button>
                  </Space>
                </Item>
              </Row>
            </Form>
          </div>
        </div>

        <div className={style['table-container']}>
          <Table loading={this.state.loading} columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={v => this.tableChange(v)} />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(ArbitratorList)
